<template>
  <a-modal
    :title="title"
    :maskClosable="false"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <div>
      <a-row>
        <a-col>
          <div class="mb10">已选机台：{{ chose.length }}台</div>
          <div class="tag-list">
            <a-tag v-for="(tag, i) in tags" :key="i" size="small" color="blue">
              {{ tag }}
              <span style="cursor: pointer;font-size: 15px;" @click="closeTag(tag, i)">×</span>
            </a-tag>
          </div>
        </a-col>
      </a-row>
      <div class="box mb10">
        <div class="content">
          <template v-if="isEquipment">
            <my-checkbox-group v-model:value="chose" style="width: 100%" @change="toggleChose" :enable-drag="true">
              <div class="equipment-scope" v-for="(row, index) in equipList" :key="index">
                <div class="title-cj">{{ row.cj }}</div>
                <my-checkbox-button
                  :value="row.cj + item.deviceNo + '/' + item.id"
                  v-for="(item, i) in row.devSnArea"
                  :key="i"
                >
                  {{ item.deviceNo }}
                </my-checkbox-button>
              </div>
            </my-checkbox-group>
          </template>
          <my-checkbox-group v-else v-model="chose" @change="toggleChose" :enable-drag="true">
            <my-checkbox-button :value="item.deviceNo + '/' + item.id" v-for="(item, i) in equipList" :key="i">
              {{ item.deviceNo }}
            </my-checkbox-button>
          </my-checkbox-group>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script>
import MyCheckboxGroup from '@/components/myCheckbox/MyCheckboxGroup.vue'
import MyCheckboxButton from '@/components/myCheckbox/MyCheckboxButton.vue'
import { httpAction } from '@/api/manage'
import { getDevice } from '@/api/customApi'
import JEditor from '@/components/jeecg/JEditor'
import JSwitch from '@/components/jeecg/JSwitch'
import { editDailyPlanPreSpin } from '../../../../api/customApi'

export default {
  props: ['time'],
  name: 'JitaiModal',
  components: {
    JEditor,
    JSwitch,
    MyCheckboxGroup,
    MyCheckboxButton
  },
  data() {
    return {
      title: '选择机台',
      isEquipment: false,
      visible: false,
      row: {},
      model: {},
      confirmLoading: false,
      selectDeviceIds: [],
      device: [],
      chose: [],
      tags: [],
      equipList: [],
      url: {
        add: '/crm_daily_plan_spun_yarn/crmDailyPlanSpunYarn/add',
        edit: '/crm_daily_plan_spun_yarn/crmDailyPlanSpunYarn/edit'
      }
    }
  },
  created() {},
  methods: {
    show(records, param, isAddTable, changeEdit = false) {
      this.changeEdit = changeEdit
      this.visible = true
      this.row = Object.assign({}, records)
      this.param = param
      switch (param) {
        case 'QingHua':
          this.gongxu = '1'
          break
        default:
          this.gongxu = '1'
      }
      // this.isEquipment = this.param.indexOf('equipmentScope') > -1
      this.isEquipment = true
      // this.gongxu = param == 'equipmentScope' ? '粗纱' : this.row.gongxu;
      this.cj = this.row.cj || this.row.workshop
      this.chose = []
      this.tags = []
      this.addTable = isAddTable
      if (isAddTable || param == 'jakt' || param == 'ybkt') {
        this.addTable = isAddTable
        // 新增情况下修改字段，由于字段的数据已经为{cj:'',devSnArea:[]}的格式，所以需改为 [cj+devSn,...]的形式
        if (this.isEquipment) {
          let equipmentScopeArr = []
          records[param].map(item => {
            item.devSnArea.map(t => {
              equipmentScopeArr.push(item.cj + t.devSn + '/' + t.deviceId)
            })
          })
          this.chose = equipmentScopeArr
        } else {
          this.chose = records[param]
        }
      } else {
        records[param]
          ? records[param].forEach(item => {
              this.chose.push(item.workshopDictText + item.deviceNo + '/' + item.id)
            })
          : null
      }
      this.$nextTick(() => {
        this.getDevSn()
      })
    },
    getDevSn() {
      const that = this
      let query = {
        // id: this.row.id,
        workingProcedure: this.gongxu, //工序
        time: this.time,
        cj: this.cj
      }
      if (this.isEquipment) {
        delete query['cj']
      }
      if (this.changeEdit) {
        query.changePlanRecordFlag = true
      }
      getDevice(query).then(res => {
        if (res.success) {
          that.device = res.result.records
          that.equipList = res.result.records
          if (this.isEquipment) {
            // 创建一个空数组用于存储按照 "workshop_dictText" 分组后的数据
            const groupedDevice = []
            // 循环遍历设备数据
            that.device.forEach(device => {
              const workshopText = device.workshop_dictText
              // 查找是否存在相应的车间分组
              let workshopGroup = groupedDevice.find(group => group.cj === workshopText)
              // 如果不存在则创建一个新的分组
              if (!workshopGroup) {
                workshopGroup = {
                  cj: workshopText,
                  devSnArea: []
                }
                groupedDevice.push(workshopGroup)
              }
              // 添加设备到相应的车间分组中
              workshopGroup.devSnArea.push(device)
            })
            // 在这里使用groupedDevice，它包含了按照 "workshop_dictText" 分组后的数据
            that.equipList = groupedDevice
          }
          setTimeout(() => {
            this.$nextTick(() => {
              this.toggleChose(this.chose)
            })
          })
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.chose = []
      this.equipList = []
    },

    handleOk() {
      if (this.addTable) {
        if (this.isEquipment) {
          let paramArr = this.getEquipmentScopeParam(this.chose)
          this.$emit('getDevSnArr', this.param, paramArr, this.selectDeviceIds)
        } else {
          this.$emit('getDevSnArr', this.param, this.chose)
        }
        this.close()
      } else {
        let query = {
          id: this.row.id,
          company: this.row.company,
          workshop: this.row.workshop,
          floor: this.row.floor,
          adeviceIds: this.row.adeviceIds,
          abProductType: this.row.abProductType,
          bdeviceIds: this.row.bdeviceIds,
          bbProductType: this.row.bbProductType,
          cdeviceIds: this.row.cdeviceIds,
          cbProductType: this.row.cbProductType,
          unOpen: this.row.unOpen,
          temOutput: this.row.temOutput,
          speedSet: this.row.speedSet,
          abStartTime: this.row.abStartTime,
          abEndTime: this.row.abEndTime,
          bbStartTime: this.row.bbStartTime,
          bbEndTime: this.row.bbEndTime,
          cbStartTime: this.row.cbStartTime,
          cbEndTime: this.row.cbEndTime,
          planTime: this.row.planTime,
          process: this.row.process,
          bproductType: this.row.bproductType
        }
        if (this.param == 'preSpinDevices') {
          query.preSpinDeviceIds = this.selectDeviceIds.join(',')
        } else if (this.param == 'adevices') {
          query.adeviceIds = this.selectDeviceIds.join(',')
        } else if (this.param == 'bdevices') {
          query.bdeviceIds = this.selectDeviceIds.join(',')
        } else if (this.param == 'cdevices') {
          query.cdeviceIds = this.selectDeviceIds.join(',')
        }
        editDailyPlanPreSpin(query).then(res => {
          if (res.success) {
            this.$message.success('修改成功')
          }
          this.close()
          this.$parent.searchQuery()
        })
      }
    },
    handleCancel() {
      this.close()
    },
    closeTag(val, index) {
      let cj = null,
        str = null,
        arrSplit = null
      if (this.isEquipment) {
        cj = val.substring(0, 2)
        str = val.substring(3)
        arrSplit = str.split('~#')
      } else {
        str = val.substring(1)
        arrSplit = str.split('~#')
      }
      let arr = [parseInt(arrSplit[0]), parseInt(arrSplit[1])]
      let test = []
      for (let i = 0; i < arr[1] - arr[0] - 1; i++) {
        test.push(arr[0] + 1 * (i + 1))
      }
      arr.splice(1, 0, ...test)
      // 去掉相同项
      let final = []
      for (let i = 0; i < this.chose.length; i++) {
        for (let j = 0; j < arr.length; j++) {
          // 粗纱特殊情况
          const item = this.isEquipment ? cj + arr[j] : arr[j]
          if (this.chose[i].split('/')[0] == item) {
            this.chose[i] = ''
            break
          }
        }
      }
      for (let i = 0; i < this.chose.length; i++) {
        if (this.chose[i] != '') {
          final.push(this.chose[i])
        }
      }
      this.tags.splice(index, 1)
      if (this.tags.length == 0) {
        this.selectDeviceIds = []
      }
      this.chose = final
    },
    getSeiresDevsnCs(arr) {
      let chose = []
      let paramArr = this.getEquipmentScopeParam(arr)
      paramArr.map(item => {
        item.devSnArea.sort((a, b) => a.devSn - b.devSn) // 根据 devSn 属性排序
        let devStrArr = this.getSeiresDevsn(item.devSnArea)
        devStrArr = devStrArr.map(t => item.cj + t)
        chose = chose.concat(devStrArr)
      })
      return chose
    },
    getEquipmentScopeParam(arr) {
      let paramArr = []
      let deviceIds = []
      arr.map(item => {
        let cj = item.substring(0, 2)
        let devSn = item.substring(2).split('/')[0]
        let deviceId = item.substring(2).split('/')[1]
        //获取选择的设别ID列表
        deviceIds.push(deviceId)
        this.selectDeviceIds = deviceIds
        //处理数据
        let index = paramArr.findIndex(find => find.cj == cj)
        if (index > -1) {
          paramArr[index]['devSnArea'].push({
            devSn,
            deviceId
          })
        } else {
          paramArr.push({
            cj,
            devSnArea: [
              {
                devSn,
                deviceId
              }
            ]
          })
        }
        // if (index > -1) {
        //   paramArr[index]['devSnArea'].push(devSn)
        // } else {
        //   paramArr.push({
        //     cj,
        //     devSnArea: [devSn]
        //   })
        // }
      })
      return paramArr
    },
    toggleChose(val) {
      console.log(val)
      if (val) {
        let arr = [].concat(val)
        if (arr.length == 0) {
          this.selectDeviceIds = []
        }
        if (this.isEquipment) {
          this.tags = this.getSeiresDevsnCs(arr)
        } else {
          arr = arr.sort(function(a, b) {
            return a - b
          })
          this.tags = this.getSeiresDevsn(arr)
        }
      } else {
        this.tags = []
        this.selectDeviceIds = []
      }
    },
    // 获取连续车台
    getSeiresDevsn(arr) {
      var result = [],
        i = 0,
        str = []
      if (arr.length > 0) {
        result[i] = [arr[0].devSn]
        arr.reduce(function(prev, cur) {
          parseInt(cur.devSn) - parseInt(prev.devSn) === 1 ? result[i].push(cur.devSn) : (result[++i] = [cur.devSn])
          return cur
        })
        result.map(item => {
          if (item.length > 1) {
            str.push(`#${item[0]}~#${item[item.length - 1]}`)
          } else {
            str.push(`#${item[0]}`)
          }
        })
      } else {
        str = []
      }
      return str
    }
  }
}
</script>

<style scoped lang="less">
.box {
  border: 1px solid #dee0e3;
  border-radius: 2px;
  overflow: auto;
  box-sizing: border-box;
  margin-top: 15px;
}

.content {
  width: 100%;
  padding: 5px 15px;

  .grid {
    display: grid;
    grid-template-columns: repeat(37, 25px);
    grid-column-gap: 8px;
    grid-row-gap: 15px;
  }

  .split {
    grid-column: span 2;
  }

  .wall {
    position: relative;

    &:after {
      display: block;
      content: '';
      position: absolute;
      left: 41px;
      top: -21px;
      width: 5px;
      height: 499px;
      background: rgba(53, 65, 86, 0.5);
      border: 1px solid #354156;
    }
  }

  .el-checkbox-button {
    width: 25px;
    height: 80px;
    border-radius: 2px;

    .el-checkbox-button__inner {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      border: none;
      background: #f1f5f8;
      color: #4a576c;
      font-size: 16px;
      padding: 0;
      box-shadow: none;
    }

    &.is-checked {
      .el-checkbox-button__inner {
        background: #e1f0ff;
        color: #2c67f6;
      }
    }

    &.is-disabled {
      .el-checkbox-button__inner {
        background: #e3e3e3;
        color: rgba(74, 87, 108, 0.3);
      }
    }
  }
}

.mb10 {
  margin-bottom: 10px;
}

.equipment-scope {
  padding: 10px 0;
  border-bottom: 1px solid #dee0e3;

  &:last-child {
    border-bottom: none;
  }
}

.title-cj {
  color: #333;
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 6px;
}
</style>
